<template>
  <div class="article-list" id="article-list">
    <van-pull-refresh v-model="isRefreshLoading" @refresh="onRefresh"  :success-text="refreshSuccessText"
    :success-duration="1500">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="(item, index) in list"
          :key="index"
          :article="item"
        ></article-item>
        <!-- <van-cell

        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null, // 请求下一页数据的时间戳
      error: false,
      isRefreshLoading: false,
      refreshSuccessText: ''
    }
  },
  created () {},
  methods: {
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.item.id,
          timestamp: Date.now(),
          with_top: 1 // 是否置顶的参数
        })
        const { results } = data.data
        this.list.unshift(...results)
        // 3. 关闭下拉刷新的 loading 状态
        this.isRefreshLoading = false
        // 提示成功
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (error) {
        this.isRefreshLoading = false // 关闭下拉刷新的 loading 状态
        this.refreshSuccessText = '刷新失败'
      }
    },
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.item.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1 // 是否置顶的参数
        })
        // 测试一下
        // if (Math.random() > 0.5) {
        //   JSON.parse('wrwerer')
        // }
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        // 4. 判断数据是否加载结束
        if (results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没有数据了，设置加载状态结束，不再触发上拉加载更多了
          this.finished = true
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
#article-list {
  height: 86vh;
  overflow: auto;
}
</style>
